
const mysqlUtil = require("./mysqlUtil");

const config = require('../config')

const axios = require('axios')

function getDistance(lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    console.log(lat1, lng1, lat2, lng2)

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    return distance;
}

// 发送提醒短信
async function sendReminderSms(phone, receiverName, processName, processStatus) {
    return axios({
        method: "post",
        data: {
            phoneNumber: phone,
            name: receiverName,
            processName: processName,
            processStatus: processStatus,
            secret: config.sms.secret
        },
        url: config.sms.url,
        // timeout: 5000
    })
}

// 给用户发送提醒短信
async function sendReminderSmsToUser(uid, processName, processStatus) {
    let res = await mysqlUtil.execute('SELECT name, phone FROM tb_user WHERE id = ? LIMIT 1', [uid])
    if (res.length == 0) return console.log('用户不存在')
    let { name, phone } = res[0]
    if (!phone) return console.log('用户没有手机号', uid)
    return sendReminderSms(phone, name, processName, processStatus)
}

// 发送验证码短信
async function sendVerifyCode(phone, code) {
    return axios({
        method: "post",
        data: {
            phoneNumber: phone,
            code,
            secret: config.sms.secret
        },
        url: config.sms.codeUrl,
        // timeout: 5000
    })
}

// 给用户发送验证码短信
async function sendVerifyCodeToUser(uid, code) {
    let res = await mysqlUtil.execute('SELECT phone FROM tb_user WHERE id = ? LIMIT 1', [uid])
    if (res.length == 0) return console.log('用户不存在')
    let { phone } = res[0]
    console.log('sendVerifyCodeToUser', uid, code, phone)
    if (!phone) return console.log('用户没有手机号', uid)
    return sendVerifyCode(phone, code)
}

module.exports = {
    getDistance,
    sendReminderSmsToUser,
    sendVerifyCodeToUser
}